<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 基本信息 -->
      <el-divider content-position="left">基本信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="司机姓名" prop="driverName">
            <el-input v-model="formData.driverName" placeholder="请输入司机姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idNumber">
            <el-input v-model="formData.idNumber" placeholder="请输入身份证号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="驾驶证号" prop="driverLicenseNo">
            <el-input v-model="formData.driverLicenseNo" placeholder="请输入驾驶证号" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 证件照片上传 -->
      <el-divider content-position="left">证件照片</el-divider>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="身份证正面" prop="idCardFrontImg">
            <div class="upload-container">
              <el-upload
                class="certificate-uploader"
                :show-file-list="false"
                :before-upload="beforeUpload"
                action="#"
                :http-request="(options) => handleImageUpload(options, 'idCardFrontImg')"
              >
                <img v-if="formData.idCardFrontImg" :src="formData.idCardFrontImg" class="certificate-image" />
                <div v-else class="upload-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <div class="upload-text">上传身份证正面</div>
                </div>
              </el-upload>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="身份证背面" prop="idCardBackImg">
            <div class="upload-container">
              <el-upload
                class="certificate-uploader"
                :show-file-list="false"
                :before-upload="beforeUpload"
                action="#"
                :http-request="(options) => handleImageUpload(options, 'idCardBackImg')"
              >
                <img v-if="formData.idCardBackImg" :src="formData.idCardBackImg" class="certificate-image" />
                <div v-else class="upload-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <div class="upload-text">上传身份证背面</div>
                </div>
              </el-upload>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="驾驶证照片" prop="driverLicenseImg">
            <div class="upload-container">
              <el-upload
                class="certificate-uploader"
                :show-file-list="false"
                :before-upload="beforeUpload"
                action="#"
                :http-request="(options) => handleImageUpload(options, 'driverLicenseImg')"
              >
                <img v-if="formData.driverLicenseImg" :src="formData.driverLicenseImg" class="certificate-image" />
                <div v-else class="upload-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <div class="upload-text">上传驾驶证照片</div>
                </div>
              </el-upload>
            </div>
          </el-form-item>
        </el-col>
      </el-row>



      <!-- 其他信息 -->
      <el-divider content-position="left">其他信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="网约车驾驶员证">
            <el-input v-model="formData.rideHailingLicense" placeholder="请输入网约车驾驶员证" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务城市">
            <el-input v-model="formData.serviceCity" placeholder="请输入服务城市" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="紧急联系人">
            <el-input v-model="formData.emergencyContact" placeholder="请输入紧急联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="紧急联系电话">
            <el-input v-model="formData.emergencyContactPhone" placeholder="请输入紧急联系电话" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 银行信息 -->
      <el-divider content-position="left">银行信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="银行名称">
            <el-input v-model="formData.bankName" placeholder="请输入银行名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="银行账号">
            <el-input v-model="formData.bankAccount" placeholder="请输入银行账号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开户人姓名">
            <el-input v-model="formData.accountHolder" placeholder="请输入开户人姓名" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">提交认证</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ElLoading, ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadRequestOptions } from 'element-plus'
import * as FileApi from '@/api/infra/file'
import * as DriverAuthApi from '@/api/system/driver-auth'

defineOptions({ name: 'DriverAuthForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('司机认证') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const ocrLoading = ref(false) // OCR识别加载中
const ocrResult = ref<any>(null) // OCR识别结果

// 表单数据
const formData = ref({
  driverName: '',
  idNumber: '',
  driverLicenseNo: '',
  idCardFrontImg: '',
  idCardBackImg: '',
  driverLicenseImg: '',
  rideHailingLicense: '',
  serviceCity: '',
  emergencyContact: '',
  emergencyContactPhone: '',
  bankName: '',
  bankAccount: '',
  accountHolder: ''
})

// 表单校验规则
const formRules = reactive({
  driverName: [{ required: true, message: '司机姓名不能为空', trigger: 'blur' }],
  idNumber: [
    { required: true, message: '身份证号不能为空', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  driverLicenseNo: [{ required: true, message: '驾驶证号不能为空', trigger: 'blur' }],
  idCardFrontImg: [{ required: true, message: '身份证正面照片不能为空', trigger: 'change' }],
  idCardBackImg: [{ required: true, message: '身份证背面照片不能为空', trigger: 'change' }],
  driverLicenseImg: [{ required: true, message: '驾驶证照片不能为空', trigger: 'change' }]
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  resetForm()
  
  if (type === 'create') {
    dialogTitle.value = '司机认证'
  } else if (type === 'update' && id) {
    dialogTitle.value = '修改司机认证'
    // TODO: 如果需要支持修改，可以在这里加载数据
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  
  // 提交请求
  formLoading.value = true
  try {
    await DriverAuthApi.submitDriverAuth(formData.value)
    message.success('司机认证提交成功，请等待审核')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 图片上传前的校验 */
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    message.error('图片只能是 JPG/PNG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

/** 处理图片上传 */
const handleImageUpload = async (options: UploadRequestOptions, fieldName: string) => {
  let loadingInstance: any = null
  try {
    console.log('开始图片上传，文件信息:', {
      name: options.file.name,
      size: options.file.size,
      type: options.file.type,
      fieldName
    })

    // 显示上传中状态
    loadingInstance = ElLoading.service({
      text: '图片上传中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    // 验证文件对象
    if (!options.file) {
      throw new Error('文件对象为空')
    }

    // 创建FormData对象
    const uploadFormData = new FormData()
    uploadFormData.append('file', options.file)

    console.log('准备调用FileApi.updateFile上传文件')

    // 上传文件
    const uploadResponse = await FileApi.updateFile(uploadFormData)

    console.log('FileApi.updateFile响应:', uploadResponse)

    if (!uploadResponse || !uploadResponse.data) {
      throw new Error('文件上传失败')
    }

    // 新的返回格式：{ id: xxx, url: xxx, name: xxx, size: xxx }
    const uploadResult = uploadResponse.data
    const fileUrl = uploadResult.url || uploadResult  // 兼容旧的字符串格式
    const fileId = uploadResult.id
    
    console.log('获取到文件信息:', { fileId, fileUrl, uploadResult })

    // 直接使用上传返回的URL
    formData.value[fieldName] = typeof fileUrl === 'string' ? fileUrl.trim() : fileUrl

    message.success('图片上传成功')
    
    // 关闭上传loading
    if (loadingInstance) {
      loadingInstance.close()
      loadingInstance = null
    }

    // 自动触发OCR识别
    if (fieldName === 'idCardFrontImg') {
      console.log('准备进行身份证OCR识别，uploadResult:', uploadResult)
      // 优先使用返回的ID，否则尝试从URL提取
      const ocrFileId = fileId || extractFileIdFromUrl(fileUrl)
      console.log('使用的fileId:', ocrFileId)
      await performOCR('idCard', fieldName, ocrFileId)
    } else if (fieldName === 'driverLicenseImg') {
      console.log('准备进行驾驶证OCR识别，uploadResult:', uploadResult)
      // 优先使用返回的ID，否则尝试从URL提取
      const ocrFileId = fileId || extractFileIdFromUrl(fileUrl)
      console.log('使用的fileId:', ocrFileId)
      await performOCR('drivingLicense', fieldName, ocrFileId)
    }

  } catch (error: any) {
    console.error('图片上传失败:', error)
    message.error('图片上传失败：' + (error?.message || '未知错误'))
  } finally {
    // 关闭loading
    if (loadingInstance) {
      loadingInstance.close()
    }
  }
}

/** 执行OCR识别 */
const performOCR = async (type: string, fieldName: string, fileId?: number) => {
  try {
    ocrLoading.value = true
    ocrResult.value = null

    // 如果没有传入fileId，尝试从图片URL中提取
    if (!fileId) {
      const imageUrl = formData.value[fieldName]
      if (!imageUrl) {
        message.warning('请先上传图片')
        return
      }
      fileId = extractFileIdFromUrl(imageUrl)
    }

    console.log('开始OCR识别，类型:', type, 'fileId:', fileId)

    let result
    if (type === 'idCard') {
      result = await DriverAuthApi.ocrIdCard(fileId)
    } else if (type === 'drivingLicense') {
      result = await DriverAuthApi.ocrDrivingLicense(fileId)
    }

    console.log('OCR API返回结果:', result)

    // 检查返回结果的结构，适应不同的返回格式
    let ocrData
    if (result?.data) {
      // 如果有data字段，使用data中的数据
      ocrData = result.data
    } else if (result) {
      // 如果没有data字段，直接使用result
      ocrData = result
    }

    console.log('解析后的OCR数据:', ocrData)

    if (ocrData?.status === 'success') {
      ocrResult.value = ocrData
      message.success('OCR识别成功，已自动填充表单')
      
      // 直接应用OCR结果
      applyOcrResult(ocrData)
    } else {
      const errorMsg = ocrData?.errorMessage || '识别失败'
      message.warning(`OCR识别失败：${errorMsg}，请手动填写相关信息`)
    }

  } catch (error: any) {
    console.error('OCR识别失败:', error)
    message.warning('OCR识别失败，请手动填写相关信息')
  } finally {
    ocrLoading.value = false
  }
}

/** 应用OCR识别结果 */
const applyOcrResult = (ocrData?: any) => {
  const data = ocrData || ocrResult.value
  if (!data || data.status !== 'success') {
    console.log('没有可用的OCR识别结果')
    return
  }

  console.log('开始应用OCR结果:', data)
  
  let hasAppliedData = false
  
  // 优先使用后端直接返回的表单字段数据
  if (data.driverName) {
    formData.value.driverName = data.driverName
    hasAppliedData = true
    console.log('设置姓名:', data.driverName)
  }
  
  if (data.idNumber) {
    formData.value.idNumber = data.idNumber
    hasAppliedData = true
    console.log('设置身份证号:', data.idNumber)
  }
  
  if (data.driverLicenseNo) {
    formData.value.driverLicenseNo = data.driverLicenseNo
    hasAppliedData = true
    console.log('设置驾驶证号:', data.driverLicenseNo)
  }
  
  // 如果后端没有返回直接字段，从结构化字段中解析
  if (!hasAppliedData && data.fields && data.fields.length > 0) {
    console.log('从结构化字段解析数据:', data.fields)
    
    data.fields.forEach(field => {
      const fieldName = field.fieldName
      const fieldValue = field.fieldValue

      console.log('处理字段:', fieldName, '值:', fieldValue)
      
      if (fieldValue && fieldValue.trim()) {
        const trimmedValue = fieldValue.trim()
        
        // 姓名字段匹配
        if (fieldName === '姓名' || fieldName === '姓　名') {
          formData.value.driverName = trimmedValue
          hasAppliedData = true
          console.log('设置姓名:', trimmedValue)
        }
        // 身份证号字段匹配 - 优先匹配标准字段名，避免与驾驶证号冲突
        else if (fieldName === '公民身份证号码' || fieldName === '公民身份号码' || fieldName === '身份证号码' || fieldName === '身份证号' || fieldName === '证件号码' || 
                 fieldName === '身份证' || fieldName === '号码' || fieldName === '公民身份证号' ||
                 (fieldName.includes('公民') && fieldName.includes('身份') && (fieldName.includes('号') || fieldName.includes('码'))) ||
                 (fieldName.includes('身份') && (fieldName.includes('号') || fieldName.includes('码'))) || 
                 (fieldName.includes('公民') && (fieldName.includes('号') || fieldName.includes('码')))) {
          formData.value.idNumber = trimmedValue
          hasAppliedData = true
          console.log('设置身份证号:', trimmedValue)
        }
        // 驾驶证号字段匹配
        else if (fieldName === '档案编号' || fieldName === '驾驶证号' || fieldName === '驾驶证号码' ||
                 (fieldName === '证号' && !fieldName.includes('身份'))) {
          formData.value.driverLicenseNo = trimmedValue
          hasAppliedData = true
          console.log('设置驾驶证号:', trimmedValue)
        }
        // 性别字段
        else if (fieldName === '性别') {
          console.log('识别到性别:', trimmedValue)
        }
        // 民族字段
        else if (fieldName === '民族') {
          console.log('识别到民族:', trimmedValue)
        }
        // 住址字段
        else if (fieldName === '住址') {
          console.log('识别到住址:', trimmedValue)
        }
      }
    })
  }

  // 如果结构化字段没有数据，尝试从文本中解析
  if (!hasAppliedData && data.text) {
    console.log('从文本中解析数据:', data.text)
    
    // 使用正则表达式从文本中提取信息
    const lines = data.text.split('\n')
    
    lines.forEach(line => {
      const trimmedLine = line.trim()
      
      // 匹配姓名: xxx 格式
      if (trimmedLine.includes('姓名:') || trimmedLine.includes('姓名：')) {
        const nameMatch = trimmedLine.match(/姓名[：:]\s*(.+)/)
        if (nameMatch && nameMatch[1]) {
          formData.value.driverName = nameMatch[1].trim()
          hasAppliedData = true
          console.log('从文本设置姓名:', nameMatch[1].trim())
        }
      }
      
      // 匹配身份证号: xxx 格式 或 公民身份证号码: xxx 格式
      if (trimmedLine.includes('公民身份证号码:') || trimmedLine.includes('公民身份证号码：') ||
          trimmedLine.includes('公民身份号码:') || trimmedLine.includes('公民身份号码：') ||
          trimmedLine.includes('身份证号:') || trimmedLine.includes('身份证号：') ||
          trimmedLine.includes('身份证号码:') || trimmedLine.includes('身份证号码：')) {
        const idMatch = trimmedLine.match(/(公民身份证?号码?|身份证号码?)[：:]\s*([0-9X]{15,18})/)
        if (idMatch && idMatch[2]) {
          formData.value.idNumber = idMatch[2].trim()
          hasAppliedData = true
          console.log('从文本设置身份证号:', idMatch[2].trim())
        }
      }
      
      // 如果没有明确的标签，尝试匹配纯身份证号码（15或18位）
      const idNumberMatch = trimmedLine.match(/([0-9]{15}|[0-9]{17}[0-9X])/)
      if (idNumberMatch && idNumberMatch[1] && !formData.value.idNumber) {
        formData.value.idNumber = idNumberMatch[1]
        hasAppliedData = true
        console.log('从文本匹配身份证号模式:', idNumberMatch[1])
      }
      
      // 匹配性别: xxx 格式
      if (trimmedLine.includes('性别:') || trimmedLine.includes('性别：')) {
        const genderMatch = trimmedLine.match(/性别[：:]\s*(.+)/)
        if (genderMatch && genderMatch[1]) {
          console.log('从文本识别性别:', genderMatch[1].trim())
        }
      }
      
      // 匹配民族: xxx 格式
      if (trimmedLine.includes('民族:') || trimmedLine.includes('民族：')) {
        const nationMatch = trimmedLine.match(/民族[：:]\s*(.+)/)
        if (nationMatch && nationMatch[1]) {
          console.log('从文本识别民族:', nationMatch[1].trim())
        }
      }
    })
  }

  if (hasAppliedData) {
    message.success('OCR识别结果已应用到表单')
  } else {
    message.info('OCR识别成功，但未检测到可填充的字段，请手动补充信息')
  }
}

/** 从文件URL中提取fileId */
const extractFileIdFromUrl = (url: string): number => {
  try {
    // 尝试从文件URL中提取ID，假设格式为 /admin-api/infra/file/{id}/get/xxx
    const match = url.match(/\/admin-api\/infra\/file\/(\d+)\/get/)
    if (match && match[1]) {
      return parseInt(match[1], 10)
    }
    
    // 如果提取失败，返回默认值
    console.warn('无法从 URL 中提取 fileId:', url)
    return 1
  } catch (error) {
    console.error('提取 fileId 失败:', error)
    return 1
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    driverName: '',
    idNumber: '',
    driverLicenseNo: '',
    idCardFrontImg: '',
    idCardBackImg: '',
    driverLicenseImg: '',
    rideHailingLicense: '',
    serviceCity: '',
    emergencyContact: '',
    emergencyContactPhone: '',
    bankName: '',
    bankAccount: '',
    accountHolder: ''
  }
  ocrResult.value = null
  formRef.value?.resetFields()
}
</script>

<style scoped>
.upload-container {
  text-align: center;
}

.certificate-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  display: block;
  width: 160px;
  height: 120px;
}

.certificate-uploader:hover {
  border-color: var(--el-color-primary);
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #8c939d;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 5px;
}

.upload-text {
  font-size: 12px;
}

.certificate-image {
  width: 160px;
  height: 120px;
  display: block;
  object-fit: cover;
}
</style>